package run.jingjing.websocket.endpoint;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

/**
 * @author: jingjing
 * @date: 2021/6/24
 * @description: littlebusters-webosocket demo endpoint
 */
@ServerEndpoint("/websocket/littlebusters/{topic}/{token}")
@Data
@Slf4j
public class LittlebustersEndpointDemo extends AbstractWebSocketEndpoint {

    @Override
    public Integer getUserId() {
        return null;
    }

    @Override
    public Session getSession() {
        return null;
    }

    @Override
    public void afterInitializationHook() {

    }

    @OnOpen
    @Override
    public void onOpen(@PathParam("token") String token, @PathParam("topic") String topic, Session session) {
        super.initEndpoint(this.getClass(), token, topic, session);
        log.info("user:{} login success in topic of {}", lWsSession.getUserId(), topic);
    }

    @OnMessage
    @Override
    public void onMessage(String message, Session session) {

    }

    @OnError
    @Override
    public void onError(Throwable error) {
        log.error("topic:{} occurred error", lWsSession.getTopic().getName(), error);
    }

    @OnClose
    @Override
    public void onClose() {
        EndpointManager.onClose(lWsSession);
    }

    @Override
    protected boolean checkToken(String token) {
        return true;
    }

    @Override
    protected Integer getUserIdFromToken(String token) {
        long l = System.currentTimeMillis();
        return (int) ((l & 0xFFF) ^ ((l & 0xFFF000) >>> 12));
    }
}
